package com.situ.company.project.dao;

import java.util.ArrayList;
import java.util.List;

import com.situ.company.project.model.ProjectModel;
import com.situ.company.util.FmtEmpty;
import com.situ.company.util.JDBCUtil;

public class ProjectDao {
    
    public int insert(ProjectModel model) {
        String sql = "insert into project (code,name,time) values(?,?,?,) ";
        return JDBCUtil.update(sql, model.getCode(),model.getName(),model.getTime());
    }
    
    public int deleteByCode(ProjectModel model) {
        String sql = "delete from project where code = ? ";
        return JDBCUtil.update(sql, model.getCode());
    }
    
    public int delete(ProjectModel model) {
        StringBuffer sql = new StringBuffer("delete from project ");
        List<Object> vals = appendWhere(sql, model);
        return JDBCUtil.update(sql.toString(), vals);
    }
    
    public int updateAllByCode(ProjectModel model) {
        String sql = "update project set name=?,time=? where code=? ";
        return JDBCUtil.update(sql, model.getName(),model.getTime(),model.getCode());
    }
    
    public int updateActive(ProjectModel model) {
        StringBuffer sql = new StringBuffer("update project set id=id ");
        List<Object> vals = new ArrayList<>();
        String name = model.getName();
        if(name != null) {
            sql.append(" ,name=? ");
            vals.add(name);
        }
        String time = model.getTime();
        if(time != null) {
            sql.append(" ,time=? ");
            vals.add(time);
        }
        sql.append("where code=? ");
        vals.add(model.getCode());
        return JDBCUtil.update(sql.toString(), vals);
    }
    
    
    public List<ProjectModel> selectList(ProjectModel model){
        StringBuffer sql = new StringBuffer("select code,name,time from project");
        List<Object> vals = appendWhere(sql, model);
        return JDBCUtil.queryList(sql.toString(), vals, ProjectModel.class);
    }
    
    public ProjectModel selectModel(ProjectModel model){
        StringBuffer sql = new StringBuffer("select code,name,time from project");
        List<Object> vals = appendWhere(sql, model);
        return JDBCUtil.queryModel(sql.toString(), vals, ProjectModel.class);
    }
    
    
    
    private List<Object> appendWhere(StringBuffer sql, ProjectModel model){
        List<Object> vals = new ArrayList<>();
        sql.append(" where 1=1 ");
        String code = model.getCode();
        if(!FmtEmpty.isEmpty(code)) {
            sql.append(" and code like ? ");
            vals.add(code);
        }
        String name = model.getName();
        if(!FmtEmpty.isEmpty(name)) {
            sql.append(" and name like ? ");
            vals.add(name);
        }
        String time = model.getTime();
        if(!FmtEmpty.isEmpty(time)) {
            sql.append(" and time like ? ");
            vals.add(time);
        }
        return vals;
    }

}
